Dart Map operator []
Syntax & Examples


Syntax of Map.operator []

The syntax of Map.operator [] operator is:

operator [](Object? key) → V?

This operator [] operator of Map the value for the given key, or null if key is not in the map.

Parameters

ParameterOptional/RequiredDescription
keyrequiredThe key for which to retrieve the corresponding value.


✐ Examples

1 Retrieve value for key 'b'

In this example,

  1. We create a map named map with key-value pairs.
  2. We then use the [] operator to retrieve the value associated with the key 'b'.
  3. The value corresponding to key 'b' is retrieved.
  4. We print the value to standard output.

Dart Program

void main() {
  var map = {'a': 1, 'b': 2, 'c': 3};
  var value = map['b'];
  print(value);
}

Output

2

2 Retrieve value for key 'z'

In this example,

  1. We create a map named map with key-value pairs.
  2. We then use the [] operator to retrieve the value associated with the key 'z'.
  3. The value corresponding to key 'z' is retrieved.
  4. We print the value to standard output.

Dart Program

void main() {
  var map = {'x': 'A', 'y': 'B', 'z': 'C'};
  var value = map['z'];
  print(value);
}

Output

C

3 Retrieve value for key 'vegetable'

In this example,

  1. We create a map named map with key-value pairs.
  2. We then use the [] operator to retrieve the value associated with the key 'vegetable'.
  3. The value corresponding to key 'vegetable' is retrieved.
  4. We print the value to standard output.

Dart Program

void main() {
  var map = {'fruit': 'apple', 'vegetable': 'carrot', 'grain': 'rice'};
  var value = map['vegetable'];
  print(value);
}

Output

carrot

Summary

In this Dart tutorial, we learned about operator [] operator of Map: the syntax and few working examples with output and detailed explanation for each example.